package tw.cating.karmasaver.alarm;

import java.util.Calendar;

import tw.cating.Utility.StringUtil;
import tw.cating.karmasaver.plurk.Log;
import tw.cating.karmasaver.plurk.autoPlurkActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class alarmReceiver extends BroadcastReceiver {
	private static final String ACTION_SAVEKARMA="tw.cating.karmasaver";
	Context mContext = null;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		mContext = context;
		Log.getInstance(context);
		Log.i("Alarm", "onReceive intent:" + intent.getAction());
		if (intent.getAction().equalsIgnoreCase(ACTION_SAVEKARMA)) {
			saveKarma();
		}
		
		setNextAlarm(mContext);
	}

	public static void setNextAlarm(Context context) {
		Log.getInstance(context);
		alarmAdapter mAdapter = new alarmAdapter(context);
		if (mAdapter.getCount() == 0)
			return;
		
		alarmMeta meta = new alarmMeta(0, 0);
		Calendar c = Calendar.getInstance();
		boolean bSeted = false;
		boolean bNextDay = false;
		for (int i = 0; i < mAdapter.getCount(); i ++) {
			meta = (alarmMeta)mAdapter.getItem(i);
			if (meta.mHour > c.get(Calendar.HOUR_OF_DAY)) {
				bSeted = true;
				break;
			} else if (meta.mHour == c.get(Calendar.HOUR_OF_DAY) && meta.mMin > c.get(Calendar.MINUTE)) {
				bSeted = true;
				break;
			}
		}
		
		if (bSeted == false) {
			meta = (alarmMeta)mAdapter.getItem(0);
			bNextDay = true;
		}
		
		c.set(Calendar.HOUR_OF_DAY, meta.mHour);
		c.set(Calendar.MINUTE, meta.mMin);
		c.set(Calendar.SECOND, 0);
		
		long atTimeInMillis = c.getTimeInMillis() + (bNextDay ? 86400000 : 0);
		Calendar nextAlarm = Calendar.getInstance();
		nextAlarm.setTimeInMillis(atTimeInMillis);
		Log.i("Alarm", "nextAlarm:" + StringUtil.Calendar(nextAlarm));
		
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);  
        
        Intent intent = new Intent(ACTION_SAVEKARMA);
        PendingIntent sender = PendingIntent.getBroadcast(  
        		context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    
        am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
	}
	

	boolean bWaitFinish = false;
	protected void saveKarma() {
		Intent intent = new Intent(mContext, autoPlurkActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(intent);
	}
}
